package cn.yunhe.java.controller;

import cn.yunhe.java.convert.MerchantDetailConvert;
import cn.yunhe.java.dto.AppDTO;
import cn.yunhe.java.dto.MerchantDTO;
import cn.yunhe.java.service.AppService;
import cn.yunhe.java.service.IMerchantService;
import cn.yunhe.java.service.SmsService;
import cn.yunhe.java.util.SecurityUtil;
import cn.yunhe.java.vo.MerchantDetailVO;
import cn.yunhe.java.vo.MerchantRegisterVo;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.util.PhoneUtil;
import com.huiminpay.common.cache.util.SevenCowUtil;
import io.swagger.annotations.*;
//import org.apache.catalina.security.SecurityUtil;应该导入自己写的SecurityUtil
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@Api(tags = {"商户服务"},description = "商户服务--描述")
public class MerchantController {
    @Reference
    IMerchantService merchantService;

    @Reference
    AppService appService;

    @Autowired
    private SmsService smsService;

    @GetMapping("/merchants/{id}")
    @ApiOperation(value="查询商户信息",notes="根据商户id查询<font color='red'>商户信息</font><br/>" +
            "<code> public MerchantDTO queryMerchantById(@PathVariable(\"id\") Long id) {\n" +
            "        MerchantDTO merchantDTO = merchantService.queryMerchantById(id);\n" +
            "        return merchantDTO;\n" +
            "    }</code>")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value = "商户id"),
            @ApiImplicitParam(name="name",value = "商户名称")
    })
    public MerchantDTO queryMerchantById(@PathVariable("id") Long id) {
        MerchantDTO merchantDTO = merchantService.queryMerchantById(id);
        return merchantDTO;
    }

    /**
     * 获取验证码
     */
    @GetMapping("/sms")
    public String getSMSCode(@RequestParam String phone) {
        log.info("向手机号:{}发送验证码", phone);
        return smsService.sendSms(phone);
    }

//        //注册商户老方式
//        MerchantDTO merchantDTO = new MerchantDTO();
//        merchantDTO.setUsername(merchantRegister.getUsername());
//        merchantDTO.setMobile(merchantRegister.getMobile());
//        merchantService.createMerchant(merchantDTO);
//        return merchantRegister;
//    }
    @ApiOperation("注册商户")
    @ApiImplicitParam(name = "merchantRegister", value = "注册信息", required = true, dataType =
            "MerchantRegisterVo", paramType = "body")
    @PostMapping("/merchants/register")
    public MerchantRegisterVo registerMerchant(@RequestBody MerchantRegisterVo merchantRegister) {

//        测试99999未知错误
//        int i=1/0;

        //校验验证码
        smsService.checkVerifiyCode(merchantRegister.getVerifiykey(), merchantRegister.getVerifiyCode());
        //注册商户
//        MapStruct方式数据转换
//        MerchantDTO merchantDTO = MerchantRegisterConvert.INSTANCE.vo2dto(merchantRegister);

//        使用Spring自带的数据转换，把需要转换的拷贝到目标数据中
        MerchantDTO merchantDTO = new MerchantDTO();
        BeanUtils.copyProperties(merchantRegister,merchantDTO);

        // 1.校验
        if (merchantRegister == null) {
            throw new BusinessException(CommonErrorCode.E_100108);
        }
        //手机号非空校验
        if (StringUtils.isBlank(merchantRegister.getMobile())) {
            throw new BusinessException(CommonErrorCode.E_100112);
        }
        //校验手机号的合法性
        if (!PhoneUtil.isMatches(merchantRegister.getMobile())) {
            throw new BusinessException(CommonErrorCode.E_100109);
        }
        //联系人非空校验
        if (StringUtils.isBlank(merchantRegister.getUsername())) {
            throw new BusinessException(CommonErrorCode.E_100110);
        }
        //密码非空校验
        if (StringUtils.isBlank(merchantRegister.getPassword())) {
            throw new BusinessException(CommonErrorCode.E_100111);
        }
        //验证码非空校验
        if (StringUtils.isBlank(merchantRegister.getVerifiyCode()) ||
                StringUtils.isBlank(merchantRegister.getVerifiykey())) {
            throw new BusinessException(CommonErrorCode.E_100103);
        }

        merchantService.createMerchant(merchantDTO);
        return merchantRegister;
    }

    //上传证件照
    @ApiOperation("上传证件照")
    @PostMapping("/upload")
    @ApiParam(value = "证件照",required = true)
    public String upload(@RequestParam("file") MultipartFile multipartFile) throws BusinessException, IOException {

        // 获取输入流
        InputStream is = multipartFile.getInputStream();
        String originalFilename = multipartFile.getOriginalFilename(); // 上传文件原文件名
        String ext = originalFilename.substring(originalFilename.indexOf(".")); // 截取获取扩展名
        String key = UUID.randomUUID() + ext;
        // 上传文件
        String accessPath = SevenCowUtil.update2Service(is, key);
        return accessPath;
    }

    @ApiOperation("资质申请")
    @PostMapping("/my/merchants/save")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "merchantInfo", value = "商户认证资料", required = true, dataType = "MerchantDetailVO", paramType = "body")
    })
    public void saveMerchant(@RequestBody MerchantDetailVO merchantInfo, HttpServletRequest request){

//        request.setAttribute("jsonToken","eyJtZXJjaGFudElkIjoxNDA2MjQzNTU1OTQwNTA3NjQ5LCJ1c2VyX25hbWUiOiJzdHJpbmciLCJtb2JpbGUiOiIxMjMxMjIyMiIsInRlbmFudElkIjoxMjM0NTZ9");

        //解析token，取出当前登录商户的id
        Long merchantId = SecurityUtil.getMerchantId(merchantService);

        //Long merchantId,MerchantDTO merchantDTO
        MerchantDTO merchantDTO = MerchantDetailConvert.INSTANCE.vo2dto(merchantInfo);
        merchantService.applyMerchant(merchantId,merchantDTO);
    }
    /**
     *  根据商户id 查询该商户下的应用列表
     * @author qawine
     * @return java.util.List<com.huiminpay.merchant.api.dto.AppDTO>
     * @date 2021/3/24 20:31
     */
    @ApiOperation("查询商户下的应用列表")
    @GetMapping(value = "/my/apps")
    public List<AppDTO> queryMyApps(HttpServletRequest request) {
//        request.setAttribute("jsonToken","eyJtZXJjaGFudElkIjoxNDA2MjQzNTU1OTQwNTA3NjQ5LCJ1c2VyX25hbWUiOiJzdHJpbmciLCJtb2JpbGUiOiIxMjMxMjIyMiIsInRlbmFudElkIjoxMjM0NTZ9");
        Long merchantId = SecurityUtil.getMerchantId(merchantService);
        return appService.queryAppByMerchant(merchantId);
    }

    @ApiOperation("获取登录用户的商户信息")
    @GetMapping(value="/my/merchants")
    public MerchantDTO getMyMerchantInfo(){
        Long merchantId = SecurityUtil.getMerchantId(merchantService);
        MerchantDTO merchant = merchantService.queryMerchantById(merchantId);
        return merchant;
    }


}